package com.kye.express.business.invoice_online.detail;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.databinding.FragmentElectronicInvoiceBinding;
import com.kye.express.utils.StringUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.invoice_online.GetInvoiceDetailResultBean;
import com.kye.model.bean.invoice_online.MailInvoiceResultBean;
import com.kye.model.download.DownloadInfo;
import com.kye.model.download.DownloadManager;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;

import io.reactivex.functions.Consumer;

/**
 * 电子发票
 */
public class ElectronicInvoiceFragment extends BaseAppCompatFragment implements ElectroniclnvoiceFragmentContract.ElectroniclnvoiceFragmentView {
    private static final String ARG_DATA = "data";
    private FragmentElectronicInvoiceBinding mBinding;

    private GetInvoiceDetailResultBean.SourceCodeDataBean mSourceCodeDataBean;

    private ElectroniclnvoiceFragmentContract.ElectroniclnvoiceFragmentViewPresenter mPresenter;
    private RxPermissions rxPermissions;
    private Dialog mLoadingDialog;

    public static ElectronicInvoiceFragment newInstance(GetInvoiceDetailResultBean.SourceCodeDataBean sourceCodeDataBean) {
        ElectronicInvoiceFragment fragment = new ElectronicInvoiceFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARG_DATA, sourceCodeDataBean);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_electronic_invoice, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mBinding = DataBindingUtil.bind(view);
        mPresenter = new ElectroniclnvoiceFragmentContract.ElectroniclnvoiceFragmentViewPresenter(getActivity());
        mPresenter.bind(this);
        getActivity().setTitle(getString(R.string.invoice_electronic));
        initView();
        initEvent();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
        if (mSourceCodeDataBean != null) {
            DownloadManager.getInstance().cancel(mSourceCodeDataBean.getPrintAddress());
        }
    }

    private void initView() {
        Bundle bundle = getArguments();
        if (bundle != null) {
            mSourceCodeDataBean = (GetInvoiceDetailResultBean.SourceCodeDataBean) bundle.getSerializable(ARG_DATA);
        }
        rxPermissions = new RxPermissions(getActivity());
        rxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            if (mSourceCodeDataBean != null) {
                                String fileName = mSourceCodeDataBean.getSourceCode() + ".pdf";
                                if (DownloadManager.getInstance().isFileDownloaded(fileName)) {
                                    showProgressView(false);
                                    setUpInvoiceView();
                                } else {
                                    showProgressView(false);
                                    String invoiceUrl = mSourceCodeDataBean.getPrintAddress();
                                    if (!TextUtils.isEmpty(invoiceUrl)) {
                                        mPresenter.downloadInvoice(invoiceUrl, fileName);
                                    }
                                }

                            }
                        } else {
                            ToastManager.show(getContext(), R.string.invoice_online_no_storage_permissions);
                        }
                    }
                });
    }

    private void initEvent() {
        RxView.clicks(mBinding.btnSendToEmail)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
                        View view = layoutInflater.inflate(R.layout.dialog_invoice_online_email_input, null);
                        EditText emailView = view.findViewById(R.id.edt_email);
                        new MaterialDialog.Builder(getActivity())
                                .title(R.string.invoice_online_input_email)
                                .customView(view, false)
                                .positiveText(R.string.common_send)
                                .negativeText(R.string.common_cancel)
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        if (mSourceCodeDataBean != null) {
                                            String emailString = emailView.getText().toString().trim();
                                            if (TextUtils.isEmpty(emailString)) {
                                                ToastManager.show(getActivity(), R.string.invoice_online_email_null, Toast.LENGTH_SHORT);
                                                return;
                                            }
                                            if (!StringUtils.checkEmail(emailString)) {
                                                ToastManager.show(getActivity(), R.string.invoice_online_email_error, Toast.LENGTH_SHORT);
                                                return;
                                            }
                                            mPresenter.mailInvoice(mSourceCodeDataBean.getSourceCode(), emailString);
                                        }
                                    }
                                })
                                .show();
                    }
                });
    }

    private void showProgressView(boolean show) {
        if (show) {
            mBinding.llElectronicDownloadPdf.setVisibility(View.GONE);
            mBinding.llElectronicDownloadProcess.setVisibility(View.VISIBLE);
        } else {
            mBinding.llElectronicDownloadPdf.setVisibility(View.VISIBLE);
            mBinding.llElectronicDownloadProcess.setVisibility(View.GONE);
        }
    }

    private void setUpInvoiceView() {
        String fileName = mSourceCodeDataBean.getSourceCode() + ".pdf";
        String invoiceSdcardPath = DownloadManager.getInstance().getFileSdcardPath(fileName);
        Logger.d("invoiceSdcardPath" + invoiceSdcardPath);
        mBinding.pdfView.fromFile(new File(invoiceSdcardPath))
                .defaultPage(1)
                .enableSwipe(true)
                .load();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_share_by_icon, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_share:
                ToastManager.show(getActivity(), "share", Toast.LENGTH_SHORT);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDownloadComplete() {
        showProgressView(false);
        setUpInvoiceView();
    }

    @Override
    public void onDownloading(DownloadInfo value) {
        long total = value.getTotal();
        long progress = value.getProgress();
        mBinding.progressBar.setProgress((int) (progress * 100 / total));
        mBinding.tvElectronicWaybillIng.setText("正在下载.." + "(" + progress / 1024 + "KB" + "/" + total / 1024 + "KB" + ")");
    }

    @Override
    public void onDownloadError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_LONG);
    }

    @Override
    public void onMailComplete() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onMailLoading() {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new KyeProgressDialog.Builder(getActivity())
                        .build();
            }
            mLoadingDialog.show();
        } catch (Exception e) {

        }
    }

    @Override
    public void onMailLoaded(MailInvoiceResultBean datas) {
        ToastManager.show(getActivity(), R.string.invoice_online_send_success, Toast.LENGTH_LONG);
    }

    @Override
    public void onMailApiError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onMailOtherError(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }
}
